<<<<<<< HEAD
export function setupRouterGuard(router) {
  router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    
    // 检查是否需要登录
    if (to.meta.requiresAuth && !token) {
      return next({ name: 'Login' })
    }
    
    // 检查是否需要访客状态
    if (to.meta.requiresGuest && token) {
      return next({ name: 'Home' })
    }
    
=======
import { useUserStore } from '@/stores/user'

export function setupRouterGuard(router) {
  router.beforeEach(async (to, from, next) => {
    console.log('🔍 路由守卫触发:', { 
      from: from.path, 
      to: to.path, 
      toName: to.name,
      timestamp: new Date().toISOString()
    })
    
    const userStore = useUserStore()
    console.log('当前用户状态:', {
      isAuthenticated: userStore.isAuthenticated,
      isLoggedIn: userStore.isLoggedIn,
      hasToken: !!userStore.token,
      hasUser: !!userStore.user,
      tokenLength: userStore.token?.length,
      userType: typeof userStore.user,
      token: userStore.token?.substring(0, 20) + '...' // 只显示token前20个字符
    })
    
    // 检查是否需要登录
    if (to.meta.requiresAuth) {
      console.log('⚠️ 页面需要认证:', to.path)
      
      // 如果用户已经登录，直接通过
      if (userStore.isAuthenticated && userStore.isLoggedIn && userStore.token) {
        console.log('✅ 用户已认证，允许访问:', to.path)
        return next()
      }
      
      // 如果用户状态还没有初始化，先尝试检查认证状态
      console.log('🔄 用户未认证，检查本地存储...')
      const isAuthenticated = await userStore.checkAuth()
      console.log('认证检查结果:', isAuthenticated)
      console.log('认证检查后状态:', {
        isAuthenticated: userStore.isAuthenticated,
        isLoggedIn: userStore.isLoggedIn,
        hasToken: !!userStore.token,
        hasUser: !!userStore.user
      })
      
      if (!isAuthenticated) {
        console.log('❌ 用户未认证，跳转到登录页')
        return next({ name: 'Login' })
      }
      
      console.log('✅ 认证检查成功，允许访问:', to.path)
    }
    
    // 检查是否需要访客状态
    if (to.meta.requiresGuest && userStore.isAuthenticated) {
      console.log('❌ 已登录用户不能访问访客页面，跳转到首页')
      return next({ name: 'Home' })
    }
    
    console.log('✅ 允许访问:', to.path)
>>>>>>> c61637f (所有前后端正常登录)
    next()
  })
}